<?php
namespace app\bigfile\controller;

use app\BaseController;
use think\facade\View;  // 门面方法

class Index extends BaseController
{

    /*
     * 测试大文件上传
     * */
    public function index(){
        $tmp  = '/index/index1';
        $type = input('param.type', 1, '');
        // 断点续传
        if($type == 2){
            $tmp  = '/index/index2';
        }
        if($type == 3){
            $tmp  = '/index/index3';
        }
        return view($tmp);
    }

    // 上传文件
    public function upload(){
        $file = $_FILES['tmp'];
        $type = trim(strrchr($_POST['name'], '.'),'.');
        $stat = '';
        if($file['error'] == 0){
            // 若不存在就移动此文件
            if(!file_exists('D:/www/thinkphp6/public/upload/upload.'.$type)){
                if(!move_uploaded_file($file['tmp_name'], 'D:/www/thinkphp6/public/upload/upload.'.$type)){
                    $stat = 'failed';
                }
            }else{ // 若存在就接受此文件的切片
                $content  = file_get_contents($file['tmp_name']);
                if (!file_put_contents('D:/www/thinkphp6/public/upload/upload.'.$type, $content,FILE_APPEND)) {
                    $stat = 'failed';
                }
            }
        }else{
            $stat = 'failed';
        }
        return json(['status'=>$stat]);
    }

    // 上传文件
    public function upload2() {
        // 追加文件块
        $fileName = $_FILES['file']['name'];
        file_put_contents('D:/www/thinkphp6/public/upload/' . $fileName, file_get_contents($_FILES['file']['tmp_name']), FILE_APPEND);
        return json([]);
    }

    // 检查上传进度(断点续传)
    public function fileSize(){
        // 接收文件名
        $fileName = $_GET['fileName'] ?? '';
        $fileSize = 0;
        $path     = 'D:/www/thinkphp6/public/upload/' . $fileName;
        //查询已上传文件大小
        if (file_exists($path)) {
            $fileSize = filesize($path);
        }
        return json([$fileSize]);
    }


}